package confapollo

import (
	"fmt"
	"gitee.com/dennis-mxx/gcode-common/menv"
	"gitee.com/dennis-mxx/gcode-common/mexception"
	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/env/config"
	"github.com/apolloconfig/agollo/v4/storage"
	"strings"
)

var Client agollo.Client

func InitApollo() {
	appId := menv.Get("apollo.appId").(string)
	secret := menv.Get("apollo.secret").(string)
	ip := menv.Get("apollo.ip").(string)
	namespaceName := menv.Get("apollo.namespace_name").(string)
	isBackupConfig := menv.Get("apollo.isBackup_config").(bool)

	if appId == "" {
		panic("The configuration item [apollo.app_id] does not exist ")
	}
	if secret == "" {
		panic("The configuration item [apollo.secret] does not exist ")
	}
	if ip == "" {
		panic("The configuration item [apollo.ip] does not exist ")
	}
	if namespaceName == "" {
		panic("The configuration item [apollo.namespace_name] does not exist ")
	}

	c := &config.AppConfig{
		AppID:          appId,
		Cluster:        secret,
		IP:             ip,
		NamespaceName:  namespaceName,
		IsBackupConfig: isBackupConfig,
		Secret:         secret,
	}
	client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return c, nil
	})
	if err != nil {
		panic(mexception.NewException(mexception.ERROR, fmt.Sprintf("初始化apollo配置失败 --> %s", err.Error())))
	}
	Client = client

	client.AddChangeListener(apolloChangeListener{})
	for _, item := range strings.Split(namespaceName, ",") {
		client.GetConfigCache(item).Range(func(key, value interface{}) bool {
			menv.SetSys(key.(string), value)
			return true
		})
	}
	menv.SetSys("server_name", appId)
}

type apolloChangeListener struct {
}

func (ce apolloChangeListener) OnChange(event *storage.ChangeEvent) {
	for k, v := range event.Changes {
		menv.SetSys(k, v)
	}
}
func (ce apolloChangeListener) OnNewestChange(event *storage.FullChangeEvent) {
	for k, v := range event.Changes {
		menv.SetSys(k, v)
	}
}
